package framework 
{
	/**
	 * ...
	 * @author omega
	 */
	public class KeyPad
	{
		private var buttonState:Array;
		private var buttonStatePrev:Array;
		private var arrowState:Array;
		private var arrowStatePrev:Array;
		
		private var assignButton:Array;
		private var assignArrow:Array;
		
		private static const ARROW_LEFT:uint = 0;
		private static const ARROW_UP:uint = 1;
		private static const ARROW_RIGHT:uint = 2;
		private static const ARROW_DOWN:uint = 3;
		
		
		public static const MAX_BUTTON:uint = 6;

		public function KeyPad(player:uint = 0) 
		{
			buttonState = new Array();
			buttonStatePrev = new Array();
			arrowState = new Array();
			arrowStatePrev = new Array();
			
			for (var i:uint = 0; i < MAX_BUTTON; i++) {
				buttonState.push(false);
				buttonStatePrev.push(false);
				arrowState.push(false);
				arrowStatePrev.push(false);
			}
			
			
			switch(player) {
				case 0:
					assignButton = new Array();
					assignButton.push(PadManager.KEYCODE_Z);
					assignButton.push(PadManager.KEYCODE_X);
					assignButton.push(PadManager.KEYCODE_C);
					
					assignArrow = new Array(
						PadManager.KEYCODE_LEFTARROW,
						PadManager.KEYCODE_UPARROW,
						PadManager.KEYCODE_RIGHTARROW,
						PadManager.KEYCODE_DOWNARROW
					);
					break;
				default:
					trace(player + "player no assign");
					break;
			}
		}
		
		public function endFrame():void {
			var i:uint;
			for (i = 0; i < MAX_BUTTON; i++) {
				buttonStatePrev[i] = buttonState[i];
			}
			for (i = 0; i < MAX_BUTTON; i++) {
				arrowStatePrev[i] = arrowState[i];
			}
		}
		
		public function onKeyDown(keyCode:uint):void {
			var i:uint;
			if(assignButton != null){
				for (i = 0; i < assignButton.length; i++) {
					if (keyCode == assignButton[i]) buttonState[i] = true;
				}
			}
			if(assignArrow != null){
				for (i = 0; i < assignArrow.length; i++) {
					if (keyCode == assignArrow[i]) arrowState[i] = true;
				}
			}
		}
		
		public function onKeyUp(keyCode:uint):void {
			if(assignButton != null){
				for (var i:uint = 0; i < assignButton.length; i++) {
					if (keyCode == assignButton[i]) buttonState[i] = false;
				}
			}
			
			if(assignArrow != null){
				for (i = 0; i < assignArrow.length; i++) {
					if (keyCode == assignArrow[i])arrowState[i] = false;
				}
			}
		}
		
		public function isPress(index:uint):Boolean {
			return buttonState[index];
		}
		
		public function isPush(index:uint):Boolean {
			if (buttonState[index] == true && buttonStatePrev[index] == false) {
				return true;
			}
			return false;
		}
		
		public function getX():int {
			return (arrowState[ARROW_LEFT] ? -1 : 0) + (arrowState[ARROW_RIGHT] ? 1 : 0);
		}
		
		public function getY():int {
			return (arrowState[ARROW_UP] ? -1 : 0) + (arrowState[ARROW_DOWN] ? 1 : 0);
		}
	}
}